package com.jinsilu.freight.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.location.LocationManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.amap.api.location.CoordinateConverter;
import com.amap.api.location.DPoint;
import com.blankj.utilcode.util.BusUtils;
import com.blankj.utilcode.util.LogUtils;
import com.hdgq.locationlib.LocationOpenApi;
import com.hdgq.locationlib.entity.ShippingNoteInfo;
import com.hdgq.locationlib.listener.OnResultListener;
import com.hjq.base.BaseDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.widget.view.BlankNoteCountdownView;
import com.jinsilu.freight.R;
import com.jinsilu.freight.aop.DebugLog;
import com.jinsilu.freight.aop.SingleClick;
import com.jinsilu.freight.common.MyVBActivity;
import com.jinsilu.freight.databinding.ActivityUploadLoadingBinding;
import com.jinsilu.freight.helper.CommonHelper;
import com.jinsilu.freight.helper.LocationHelper;
import com.jinsilu.freight.helper.ShowImageHelper;
import com.jinsilu.freight.http.model.HttpData;
import com.jinsilu.freight.http.request.CheckBlankNoteMoneyApi;
import com.jinsilu.freight.http.request.GetLineInfoByIdApi;
import com.jinsilu.freight.http.request.UpdateImageApi;
import com.jinsilu.freight.http.request.UploadLoadPoundsApi;
import com.jinsilu.freight.http.response.BankInfoBean;
import com.jinsilu.freight.http.response.FileBean;
import com.jinsilu.freight.http.response.TmsLineBean;
import com.jinsilu.freight.http.response.WaybillBean;
import com.jinsilu.freight.other.AppConfig;
import com.jinsilu.freight.other.IntentKey;
import com.jinsilu.freight.other.MTLConstants;
import com.jinsilu.freight.ui.fragment.UnfinishedWaybillFragment;
import com.jinsilu.freight.widget.BrowserView;

import java.io.File;
import java.util.List;

/**
 * 上传装车磅单
 *
 * @author yangyang
 * @time 2020-11-16 16:40
 */
public class UploadLoadingActivity extends MyVBActivity<ActivityUploadLoadingBinding> {

    private String picUrl;
    private WaybillBean waybillBean;

    private BankInfoBean bankInfoBean;

    private double mLongitude = -1; // 经度
    private double mLatitude = -1; //  纬度
    private String mLocateAddress = ""; // 定位地址

    private DPoint mStartLatLng;
    private DPoint mEndLatLng;

    //是否同意开通白条支付 0  否 1 是
    private int applyWhite = -1;

    public static final int NO = 0;
    public static final int YES = 1;

    @DebugLog
    public static void start(Context context, WaybillBean waybillBean) {
        Intent intent = new Intent(context, UploadLoadingActivity.class);
        intent.putExtra(IntentKey.WAYBILL, waybillBean);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {

        setOnClickListener(binding.ivUploadLoading, binding.tvSelectBank, binding.tvBtnSave);

        waybillBean = getSerializable(IntentKey.WAYBILL);

        // 装车打回、卸车打回、装卸车打回
        if (isBackToWaybill() && !CommonHelper.isShowBlankNote()) {
            binding.llIsShowBlankNote.setVisibility(View.GONE);
        } else {
            binding.llIsShowBlankNote.setVisibility(View.VISIBLE);
        }

        binding.rbYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                applyWhite = 1;
                binding.rbNo.setChecked(false);
                binding.rbYes.setChecked(true);
                String weight = binding.etLoadingWeight.getText().toString().trim();
                if (TextUtils.isEmpty(weight)) {
                    toast("请输入装车净重");
                    applyWhite = -1;
                    binding.rbYes.setChecked(false);
                    return;
                }
                checkMoney(weight);
            }
        });

        binding.rbNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 调用拒绝按钮
                applyWhite = 0;
                binding.rbNo.setChecked(true);
                binding.rbYes.setChecked(false);
                binding.tvBlankNoteAmount.setText("0");
            }
        });

        binding.etLoadingWeight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String input = editable.toString();
                if (input.isEmpty()) {
                    return;
                }

                double number = Double.parseDouble(input);
                if (number < 0 || number > 200) {
                    binding.etLoadingWeight.setError("请输入1-200之间的数字");
                    binding.etLoadingWeight.setText("");
                }
            }
        });

    }

    @Override
    protected void initData() {

        getLineInfoById(waybillBean.getLineId());

        if (XXPermissions.isGranted(this, new String[]{Permission.ACCESS_FINE_LOCATION, Permission.ACCESS_COARSE_LOCATION})) {
            initLocationSDK();
        } else {
            failedOnLocation();
        }

        binding.tvBlankNoteAmount.setText("0");

    }

    private void initLocationSDK() {
        // 自定义定位方法
        LocationHelper.init(this);
        LocationHelper.getCurrentLocation(location -> {
            if (null == location) return;
            mLatitude = location.getLatitude();
            mLongitude = location.getLongitude();
            mLocateAddress = location.getAddress();
        });
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        initLocationSDK();
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION);
        filter.addAction(Intent.ACTION_PROVIDER_CHANGED);
        registerReceiver(gpsSwitchStateReceiver, filter);
    }

    private final BroadcastReceiver gpsSwitchStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (LocationManager.PROVIDERS_CHANGED_ACTION.equals(intent.getAction())) {
                // Make an action or refresh an already managed state.
                LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
                boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//                boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

                if (isGpsEnabled) {
                    initLocationSDK();
                } else {
                    failedOnLocation();
                }
            }
        }
    };

    private void failedOnLocation() {
        mLatitude = -1;
        mLongitude = -1;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocationHelper.destroy();
        unregisterReceiver(gpsSwitchStateReceiver);
    }

    @SingleClick
    @Override
    public void onClick(View v) {
        if (binding.ivUploadLoading.equals(v)) { // 上传图片
            startImageSelectActivity(0);
        } else if (binding.tvSelectBank.equals(v)) { // 选择银行卡
            Intent intent = new Intent(this, MyBankManageActivity.class);
            intent.putExtra("load", "");
            startActivityForResult(intent, (resultCode, data) -> {
                if (resultCode == RESULT_OK && null != data) {
                    bankInfoBean = (BankInfoBean) data.getSerializableExtra("bankInfo");
                    if (null != bankInfoBean) {
                        setBankInfo(bankInfoBean);
                    }
                }
            });
        } else if (binding.tvBtnSave.equals(v)) {
            if (TextUtils.isEmpty(picUrl)) {
                toast("请上传装车磅单图片");
                return;
            }

            String weight = binding.etLoadingWeight.getText().toString().trim();
            if (TextUtils.isEmpty(weight)) {
                toast("请输入装车净重");
                return;
            }

            String bankNum = binding.tvSelectBank.getText().toString().trim();
//            if (TextUtils.isEmpty(bankNum)) {
//                toast("请选择收款账户");
//                return;
//            }
            // 保存
            if (-1 == mLatitude || mLongitude == -1 || TextUtils.isEmpty(mLocateAddress)) {
                initLocationSDK();
            }
            /**
             * 发货、收货地址经纬度为空
             */
            if (null == mStartLatLng || mEndLatLng == null) {
                toast("请联系货主修改线路的收发货经纬度");
                return;
            }
//            if (-1 == applyWhite && !isBackToWaybill()) {
//                toast("请选择是否开通白条");
//                return;
//            }

            /*
             * 磅单净重>34吨
             * 运单状态为打回状态下
             * 网货 SDK 100045:运单已结束情况下不再调用上传接口
             * 这些情况 直接上传装车磅单
             */
            if (Float.parseFloat(weight) > 34 || isBackToWaybill()) {
                BusUtils.postSticky(HomeActivity.TAG_CANCEL_COUNT_DOWN); // 发送消息取消倒计时上传数据
                saveInfo();
            } else if (!TextUtils.isEmpty(AppConfig.getAppSecurity()) && !TextUtils.isEmpty(AppConfig.getEnterpriseSenderCode())) {
                // 网货SDK所需不为空则初始化
                showDialog();
                startLocation(waybillBean); // 上传定位SDK成功后调用上传卸车磅单接口
            } else {
                saveInfo();
            }
        }
    }

    /**
     * @return 是否打回运单
     */
    private boolean isBackToWaybill() {
        return 4 == waybillBean.getWaybillStatus() || 5 == waybillBean.getWaybillStatus() || 6 == waybillBean.getWaybillStatus();
    }

    /**
     * 网络货运SDK 开始定位上传装车运单号
     */
    private void startLocation(WaybillBean waybillBean) {
        LogUtils.e(mEndLatLng.getLongitude(), mEndLatLng.getLatitude());
        ShippingNoteInfo shippingNoteInfo = new ShippingNoteInfo();
        shippingNoteInfo.setShippingNoteNumber(waybillBean.getWaybillNumber());
        shippingNoteInfo.setSerialNumber(MTLConstants.SERIALNUMBER);
        shippingNoteInfo.setStartCountrySubdivisionCode(waybillBean.getConsignorZoningCode());
        shippingNoteInfo.setEndCountrySubdivisionCode(waybillBean.getConsigneeZoningCode());
        shippingNoteInfo.setStartLongitude(mStartLatLng.getLongitude());
        shippingNoteInfo.setStartLatitude(mStartLatLng.getLatitude());
        shippingNoteInfo.setEndLongitude(mEndLatLng.getLongitude());
        shippingNoteInfo.setEndLatitude(mEndLatLng.getLatitude());
        shippingNoteInfo.setStartLocationText(waybillBean.getConsignorAddress());
        shippingNoteInfo.setEndLocationText(waybillBean.getConsigneeAddress());
        shippingNoteInfo.setVehicleNumber(waybillBean.getVehicleNumber());
        shippingNoteInfo.setDriverName(waybillBean.getDriverName());
        ShippingNoteInfo[] shippingNoteNumbers = new ShippingNoteInfo[]{shippingNoteInfo};
        /*
          context 上下文
          appId 网络货运企业 APP 的唯一标识
          appSecurity 网络货运企业在省平台申请的接入安全码
          enterpriseSenderCode 网络货运企业在省平台申请的企业发送代码
          environment 环境:“debug”接入测试环境，“release”接入正式环境。 App
          listener 返回结果回调函数
         */
        LocationOpenApi.auth(this, AppConfig.getPackageName(), AppConfig.getAppSecurity(), AppConfig.getEnterpriseSenderCode(), AppConfig.getBuildType(), new OnResultListener() {
            @Override
            public void onFailure(String errorCode, String errorMsg) {
                hideDialog();
                // 失败不能影响自己的业务
                saveInfo();
                LogUtils.e(String.format("监管平台SDK认证错误：ErrorCode%s ErrorMsg%s", errorCode, errorMsg));
            }

            @Override
            public void onSuccess(List<ShippingNoteInfo> list) {
                /*
                 * context 上下文
                 * vehicleNumber 车牌号
                 * driverName 司机姓名
                 * remark 备注
                 * shippingNoteNumbers 运单信息列表
                 * listener 结果回调函数
                 */
                LocationOpenApi.start(getContext(), waybillBean.getVehicleNumber(), waybillBean.getDriverName(), "", shippingNoteNumbers, new OnResultListener() {
                    @Override
                    public void onFailure(String errorCode, String errorMsg) {
                        hideDialog();
                        // 失败不能影响自己的业务
                        saveInfo();
                        LogUtils.e(String.format("监管平台SDK启动错误：ErrorCode%s ErrorMsg%s", errorCode, errorMsg));
                    }

                    @Override
                    public void onSuccess(List<ShippingNoteInfo> list) {
                        hideDialog();
                        if (!list.isEmpty()) {
                            BusUtils.postSticky(HomeActivity.TAG_START_COUNT_DOWN, list); // 发送消息开始倒计时上传数据
                        }
                        saveInfo();
                    }
                });

            }
        });
    }

    private void setBankInfo(BankInfoBean bankInfoBean) {
        binding.bankTypeLayout.setVisibility(View.VISIBLE);
        binding.tvSelectBank.setText(bankInfoBean.getBankName());
        binding.tvBankType.setText(String.format("%s-%s", bankInfoBean.getBankName(), bankInfoBean.getCardType()));
        binding.payeeNameLayout.setVisibility(View.VISIBLE);
        binding.tvPayeeName.setText(bankInfoBean.getAccountHolder());
        binding.payeeIdLayout.setVisibility(View.VISIBLE);
        binding.tvPayeeIdNumber.setText(bankInfoBean.getIdentityCard());
    }

    /**
     * 提交表单
     */
    public void saveInfo() {
        if (TextUtils.isEmpty(picUrl)) {
            toast("请上传装车磅单图片");
            return;
        }

        String weight = binding.etLoadingWeight.getText().toString().trim();
        if (TextUtils.isEmpty(weight)) {
            toast("请输入装车净重");
            return;
        }

//        String bankNum = binding.tvSelectBank.getText().toString().trim();
////        if (TextUtils.isEmpty(bankNum)) {
////            toast("请选择收款账户");
////            return;
////        }

//        String oilAccount = binding.etOilCardNum.getText().toString().trim();
        String backId = "";
        if(bankInfoBean != null){
            backId = String.valueOf(bankInfoBean.getId());
        }
        EasyHttp.put(this)
                .api(new UploadLoadPoundsApi()
                                .setBankId(backId)
                                .setImageUrl(picUrl)
//                        .setOilAccount(oilAccount)
                                .setWaybillNumber(waybillBean.getWaybillNumber())
                                .setWeight(weight)
                                .setUploadAddress(mLocateAddress)
                                .setLongitude(String.valueOf(mLongitude))
                                .setLatitude(String.valueOf(mLatitude))
                                .setApplyWhite(applyWhite)
                )
                .request(new HttpCallback<HttpData<Void>>(this) {

                    @Override
                    public void onSucceed(HttpData<Void> data) {
                        toast(data.getMessage());
                        BusUtils.postSticky(UnfinishedWaybillFragment.TAG_NEED_TO_REFRESH_WAYBILL); // UnfinishedWaybillFragment will receive
                        finish();
                        // 网货SDK所需不为空则初始化
//                        if (!TextUtils.isEmpty(AppConfig.getAppSecurity()) && !TextUtils.isEmpty(AppConfig.getEnterpriseSenderCode())) {
//                            showDialog();
//                            startLocation(waybillBean); // 上传定位SDK成功后调用上传卸车磅单接口
//                        } else {
//                            finish();
//                        }
                    }
                });
    }

    /**
     * 启动图片选择
     */
    private void startImageSelectActivity(int index) {
        ImageSelectVBActivity.start(this, new ImageSelectVBActivity.OnPhotoSelectListener() {

            @Override
            public void onSelected(File file) {
//                File file = CommonHelper.getFileFromUri(data);
                uploadImage(file);
            }

            @Override
            public void onCancel() {
            }
        });
    }

    /**
     * 获取白条额度
     *
     * @param weight 装车净重
     */
    private void checkMoney(String weight) {
        EasyHttp.get(this)
                .api(new CheckBlankNoteMoneyApi()
                        .setUploadWeight(weight)
                        .setWaybillNumber(waybillBean.getWaybillNumber()))
                .request(new HttpCallback<HttpData<String>>(this) {
                    @Override
                    public void onSucceed(HttpData<String> result) {
//                        super.onSucceed(result);
                        binding.tvBlankNoteAmount.setText(result.getData());
                        if (binding.rbYes.isChecked()) {
                            // 弹出白条使用协议
                            new BaseDialog.Builder(UploadLoadingActivity.this)
                                    .setContentView(R.layout.dialog_blank_note_agreement)
                                    .setAnimStyle(BaseDialog.ANIM_SCALE)
                                    .setCanceledOnTouchOutside(false)
                                    //.setText(id, "我是预设置的文本")
                                    .setOnClickListener(R.id.bcv_agree, (BaseDialog.OnClickListener<BlankNoteCountdownView>) (dialog, view) -> {
                                        dialog.dismiss();
                                        // 调用保存按钮
//                                        onClick(binding.tvBtnSave);
                                    })
                                    .setOnClickListener(R.id.tv_btn_disagree, (BaseDialog.OnClickListener<TextView>) (dialog, view) -> {
                                        dialog.dismiss();
                                        // 调用拒绝按钮
                                        applyWhite = 0;
                                        binding.rbNo.setChecked(true);
                                        binding.rbYes.setChecked(false);
                                        binding.tvBlankNoteAmount.setText("0");
                                    })
                                    .addOnShowListener(dialog -> {
                                        BrowserView webView = ((BrowserView) dialog.getContentView().findViewById(R.id.wv_browser_view));
                                        if (null != webView) {
                                            webView.loadUrl(AppConfig.getAgreementUrl());
                                        }
                                        BlankNoteCountdownView countdownView = dialog.getContentView().findViewById(R.id.bcv_agree);
                                        if (null != countdownView) {
                                            countdownView.setTotalTime(10);
                                            countdownView.start();
                                        }
                                    })
                                    .addOnCancelListener(dialog -> {
                                    })
                                    .addOnDismissListener(dialog -> {
                                        BrowserView webView = ((BrowserView) dialog.getContentView().findViewById(R.id.wv_browser_view));
                                        if (null != webView) {
                                            webView.removeAllViews();
                                            webView.destroy();
                                        }
                                    })
                                    .setOnKeyListener((dialog, event) -> {
//                    toast("按键代码：" + event.getKeyCode());
                                        return false;
                                    })
                                    .show();
                        }
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                        applyWhite = 0;
                        binding.rbYes.setChecked(false);
                        binding.rbNo.setChecked(true);
                    }
                });
    }

    private void uploadImage(File file) {
        // 上传文件
        EasyHttp.post(this)
                .api(new UpdateImageApi()
                        .setImage(file))
                .request(new HttpCallback<HttpData<FileBean>>(this) {

                    @Override
                    public void onSucceed(HttpData<FileBean> data) {
//                        FileUtils.delete(file);
                        String imgUrl = data.getData().getUrl();
                        picUrl = imgUrl;
                        ShowImageHelper.showNormal(UploadLoadingActivity.this, imgUrl, binding.ivUploadLoading);
                    }
                });
    }

    /**
     * 通过线路id获取线路信息
     *
     * @param lineId 线路ID
     */
    private void getLineInfoById(String lineId) {
        // 上传文件
        EasyHttp.get(this)
                .api(new GetLineInfoByIdApi()
                        .setLineId(lineId))
                .request(new HttpCallback<HttpData<TmsLineBean>>(this) {

                    @Override
                    public void onSucceed(HttpData<TmsLineBean> data) {
                        TmsLineBean tmsLineBean = data.getData();
                        if (0.0 == tmsLineBean.getStartLatitude() || 0.0 == tmsLineBean.getStartLongitude()
                                || 0.0 == tmsLineBean.getEndLatitude() || 0.0 == tmsLineBean.getEndLongitude()) {
                            mStartLatLng = null;
                            mEndLatLng = null;
                        } else {
                            CoordinateConverter converter = new CoordinateConverter(UploadLoadingActivity.this);
                            // CoordType.GPS 待转换坐标类型
                            converter.from(CoordinateConverter.CoordType.GPS);
                            // sourceLatLng待转换坐标点 DPoint类型
                            // DPoint(double latitude, double longitude)
                            try {
                                converter.coord(new DPoint(tmsLineBean.getStartLatitude(), tmsLineBean.getStartLongitude()));
                                mStartLatLng = converter.convert();
                                converter.coord(new DPoint(tmsLineBean.getEndLatitude(), tmsLineBean.getEndLongitude()));
                                mEndLatLng = converter.convert();
                                LogUtils.e("GetStart Convert Result Latitude: ", mStartLatLng.getLatitude() + " Longitude: ", mStartLatLng.getLongitude());
                                LogUtils.e("GetEnd Convert Result Latitude: ", mEndLatLng.getLatitude() + " Longitude: ", mEndLatLng.getLongitude());
                            } catch (Exception e) {
                                LogUtils.e("GetEnd Convert Error ", e.getMessage());
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == XXPermissions.REQUEST_CODE) {
            if (XXPermissions.isGranted(this, new String[]{
                    Permission.ACCESS_FINE_LOCATION,
                    Permission.ACCESS_COARSE_LOCATION})) {
                toast("用户已经在权限设置页授予定位权限");
            } else {
                toast("用户没有在权限设置页授予权限");
            }
        }
    }

}
